package config

import (
	"fmt"
	"os"
	"pmservice/logger"

	"gopkg.in/yaml.v2"
)

type GqlServer struct {
	Host                     string `yaml:"Host"`
	Port                     int    `yaml:"Port"`
	GraphqlPath              string `yaml:"GraphqlPath"`
	GraphqlPlayGroundEnabled bool   `yaml:"GraphqlPlayGroundEnabled"`
	GraphqlPlaygroundPath    string `yaml:"GraphqlPlaygroundPath"`
}

type Gorm struct {
	AutoMigrate   bool   `yaml:"AutoMigrate"`
	SeedDb        bool   `yaml:"SeedDb"`
	LogMode       bool   `yaml:"LogMode"`
	Dialect       string `yaml:"Dialect"`
	ConnectionDsn string `yaml:"ConnectionDsn"`
}

type CenterMonitor struct {
	Host string `yaml:"Host"`
	Port int    `yaml:"Port"`
}

type WsServer struct {
	WsHost string `yaml:"WsHost"`
	WsPort int    `yaml:"WsPort"`
	WsPath string `yaml:"WsPath"`
	Host   string `yaml:"Host"`
	Port   int    `yaml:"Port"`
}

// Config --
type Config struct {
	Gorm          Gorm          `yaml:"Gorm"`
	GqlServer     GqlServer     `yaml:"GqlServer"`
	CenterMonitor CenterMonitor `yaml:"CenterMonitor"`
	WsServer      WsServer      `yaml:"WsServer"`
}

// ReadConfig .yml config file
func ReadConfig(cfgFile string) *Config {
	data, err := os.ReadFile(cfgFile)
	if err != nil {
		logger.Fatal("Cannot read config file: " + cfgFile)
	}
	// logger.Info("data:", string(data))
	cfg := Config{}
	err = yaml.Unmarshal(data, &cfg)
	if err != nil {
		logger.Panic("Config Error:", err)
	}
	return &cfg
}

// Cfg --
var Cfg *Config

func Init(path string) {
	Cfg = ReadConfig(path)
}

func GetServerAddr() string {
	return Cfg.GqlServer.Host + ":" + fmt.Sprint(Cfg.GqlServer.Port)
}
